// pages/optional/choose/index.js
const {
  citySubjectList,
  matchCustom,
  schoolReportAdd
} = require('../../../api/api')
const {
  decodeUserInfo
} = require('../../../api/login')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list1: [],
    checkedList: [],
    mainSubject: '',
    chooseList: [],
    score: 0,
    ranking: 0,
    currentRegion: {},
    subList: [{}, {}, {}, {}, {}, {}],
    length: 3,
    bottomLift: getApp().globalData.bottomLift,
    selectedData: {},
    detail: {},
    isSvip: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!wx.getStorageSync('optionalChooseFilters')) {
      var d = new Date()
      var year = d.getFullYear()
      var month = d.getMonth()
      if (month > 6) {
        year = year + 1
      }
      const obj = {
        province: wx.getStorageSync('optionalFilters').province,
        year: year
      }
      this.setData({
        selectedData: obj
      })
      wx.setStorageSync('optionalChooseFilters', obj)
    } else {
      this.setData({
        selectedData: wx.getStorageSync('optionalChooseFilters')
      })

    }
    this.initData()
  },
  initData() {
    const chooseList = wx.getStorageSync('chooseList') || []
    const mainSubject = wx.getStorageSync('mainSubject') || ''
    const mainSubjectList = chooseList.filter((item) => {
      return item.subjectsId == mainSubject
    })
    const secondSelectArray = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const firstSelect = mainSubjectList.length > 0 && mainSubjectList[0].subjectsName
    const secondSelect = secondSelectArray.map((item) => {
      return item.subjectsName
    })
    this.setData({
      currentRegion: wx.getStorageSync('userCitys') || {},
      chooseList,
      checkedList: wx.getStorageSync('ids') || [],
      firstSelect,
      secondSelect: secondSelect.join(','),
      mainSubject,
    })
    this.getCitySubject()
    this.loadData()
  },
  async loadData() {
    const {
      selectedData,
      mainSubject,
      chooseList
    } = this.data
    const mainSubjectList = chooseList.filter((item) => {
      return item.subjectsId == mainSubject
    })
    if (chooseList.length < 3) return
    const params = {
      year: selectedData.year,
      provinceId: selectedData.province,
      subjects: chooseList.map((item) => {
        return item.subjectsName
      }),
      type: mainSubjectList.length > 0 ? mainSubjectList[0].subjectsName : ''
    }
    const {
      result
    } = await matchCustom(params)
    this.setData({
      detail: result
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  async getCitySubject() {
    const code = wx.getStorageSync('userCitys').code
    // console.log('optional/choose--getCitySubject', code)
    const {
      result
    } = await citySubjectList(code)
    //首选科目
    const mainList = result.filter(function (item, index, arr0) {
      return item.isPreferred > 0
    })
    const subjectList = result.filter(function (item, index, arr0) {
      return item.isPreferred == 0
    })
    this.setData({
      list1: mainList
    })

    if (wx.getStorageSync('ids')) {
      const ids = wx.getStorageSync('ids')
      subjectList.map((item) => {
        item['choose'] = ids.indexOf(item.subjectsId) > -1
      })
    } else {
      subjectList.map((item) => {
        item['choose'] = false
      })
    }

    this.setData({
      subList: subjectList,
      length: mainList.length > 0 ? 2 : 3
    })
  },
  chooseMain(e) {
    const {
      list1,
      chooseList,
      checkedList
    } = this.data
    const {
      id,
      name
    } = e.currentTarget.dataset
    const ids = checkedList
    if (ids.indexOf(id) > -1) return
    const deleteIds = list1.filter((item) => {
      return item.subjectsId !== id
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == id
    })
    const subjectsId = deleteIds[0].subjectsId
    chooseList.map((item, index) => {
      if (item.subjectsId == subjectsId) {
        chooseList.splice(index, 1)
      }
    })
    const newList = mainSubjectList.concat(chooseList)
    const newCheckedList = newList.map((item) => {
      return item.subjectsId
    })
    this.setData({
      mainSubject: id,
      chooseList: newList,
      checkedList: newCheckedList,
      firstSelect: name,
    })
    this.loadData()
  },
  chooseSubject(e) {
    const {
      id,
      choose,
      index,
      name
    } = e.currentTarget.dataset
    var {
      subList, //学科列表
      checkedList, //已选科目id
      chooseList, //已选科目
      length,
      mainSubject,
      list1
    } = this.data
    const hookSubjectList = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == mainSubject
    })
    const hookIds = hookSubjectList.length > 0 ? hookSubjectList.map((item) => {
      return item.subjectsId
    }) : []
    const mainIds = mainSubjectList.length > 0 ? mainSubjectList.map((item) => {
      return item.subjectsId
    }) : []
    subList[index].choose = !choose
    if (choose) {
      //删除
      const index = hookIds.indexOf(id)
      hookIds.splice(index, 1)
      hookSubjectList.splice(index, 1)
    } else {
      if (hookIds.length >= length) {
        subList.map((item) => {
          if (item.subjectsId == hookIds[0]) {
            item.choose = false
          }
        })
        hookIds.splice(0, 1, id)
        hookSubjectList.splice(0, 1, subList[index])

      } else {
        hookIds.push(id)
        hookSubjectList.push(subList[index])
      }
    }
    chooseList = mainSubjectList.concat(hookSubjectList.sort((a, b) => {
      return a.id - b.id
    }))
    checkedList = mainIds.concat(hookIds)
    const secondSelectArray = hookSubjectList.map((item) => {
      return item.subjectsName
    })
    this.setData({
      subList,
      checkedList,
      chooseList,
      secondSelect: secondSelectArray.join(',')
    })
    this.loadData()

  },
  async analyse() {
    // await this.saveSubject()
    const {
      chooseList,
      mainSubject,
      firstSelect,
      secondSelect,
      currentRegion,
      selectedData
    } = this.data
    const provinceId = currentRegion.code
    const province = currentRegion.name
    const subjects = chooseList.map((item) => {
      return item.subjectsName
    })
    const params = {
      chooseList,
      mainSubject,
      firstSelect,
      secondSelect,
      provinceId,
      province,
      subjects: subjects.join(),
      year: selectedData.year
    }
    wx.navigateTo({
      url: '/pages/optional/analyse/index?params=' + encodeURIComponent(JSON.stringify(params)),
    })
  },


  onReady() {

  },

  onShow() {
    this.fetchUserInfo()
  },
  async fetchUserInfo() {
    const {
      vipType
    } = await getApp().fetchUserInfo()
    console.log(vipType)
    this.setData({
      isSvip: vipType == 'svip' ? vipType : false,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '自主选科',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})